package com.qdaily.ui.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.format.Time;

import com.qdaily.supportlibrary.util.QLog;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Qdaily工具类
 * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 4/7/15
 * Time: 14:51
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class QDUtil {
    /**
     * Description： 处理微博过去时间显示效果
     *
     * @param createAt Data 类型
     * @return { String }
     * @throws
     */
    public static String getSocialDateDisplay(long createAt) {
        long curMillis = System.currentTimeMillis();
        createAt = convertMillis(createAt);
        long diffMinute = (curMillis - createAt) / (1000 * 60);

        if (diffMinute < 30) {
            return "刚刚";
        }

        Time time = new Time();
        time.set(createAt);

        Time curTime = new Time();
        curTime.setToNow();
        if (isToday(createAt)) {
            if (diffMinute < 60)
                return diffMinute + "分钟前";

            long hour = diffMinute / 60;
            return hour + "小时前";
        }

        if (curTime.year - time.year == 1) {
            return "去年";
        }

        if (curTime.year - time.year > 1) {
            String result = time.year + "年" + (time.month + 1) + "月" + time.monthDay + "日";
            QLog.w("QDUtil", createAt + "2年前的时间:" + result);
            return result;
        }

        if (curTime.yearDay - time.yearDay == 1) {
            return "昨天";
        }

        return (time.month + 1) + "月" + time.monthDay + "日";
    }

    /**
     * Description： 处理微博过去时间显示效果
     *
     * @param createAt Data 类型
     * @return { String }
     * @throws
     */
//    public static String getSocialDateDisplay(long createAt) {
//        //定义最终返回的结果字符串。
//        String interval = null;
//
//        long millisecond = new Date().getTime() - createAt * 1000;
//
//        long second = millisecond / 1000;
//
//        if (second <= 0) {
//            second = 0;
//        }
//
//        if (second == 0) {
//            interval = "刚刚";
//        } else if (second < 30) {
//            interval = second + "秒以前";
//        } else if (second >= 30 && second < 60) {
//            interval = "半分钟前";
//        } else if (second >= 60 && second < 60 * 60) {
//            long minute = second / 60;
//            interval = minute + "分钟前";
//        } else if (second >= 60 * 60 && second < 60 * 60 * 24) {
//            long hour = (second / 60) / 60;
//            if (hour <= 3) {
//                interval = hour + "小时前";
//            } else {
//                interval = "今天" + getFormatTime(createAt, "hh");
//            }
//        } else if (second >= 60 * 60 * 24 && second <= 60 * 60 * 24 * 2) {
//            interval = "昨天" + getFormatTime(createAt, "hh");
//        } else if (second >= 60 * 60 * 24 * 2 && second <= 60 * 60 * 24 * 7) {
//            long day = ((second / 60) / 60) / 24;
//            interval = day + "天前";
//        } else if (second >= 60 * 60 * 24 * 7) {
//            interval = getFormatTime(createAt, "MM-dd");
//        } else if (second >= 60 * 60 * 24 * 365) {
//            interval = getFormatTime(createAt, "YYYY-MM-dd");
//        } else {
//            interval = "0";
//        }
//        // 最后返回处理后的结果。
//        return interval;
//    }

    /**
     * @param milliseconds
     * @return
     * @Description: 根据传入的毫秒为单位的时间, 判断是否是今天
     * @author Felix
     * @date 2014-12-27 00:55:19
     */
    public static boolean isToday(long milliseconds) {
        return DateUtils.isToday(convertMillis(milliseconds));
    }

    public static long convertMillis(long second)
    {
        String str = String.valueOf(second);
        if (str.length() == 10)
        {
            return second * 1000;
        }
        return second;
    }

    /**
     * @param milliseconds
     * @param Sdf
     * @return
     * @throws
     */
    private static String getFormatTime(long milliseconds, String Sdf) {
        return (new SimpleDateFormat(Sdf)).format(new Date(milliseconds));
    }

    /**
     * 判断是否是合法的用户名，支持6~20个字母、数字、下划线 ^[\\_a-zA-Z0-9]{5,20}$
     *
     * @param autopianum
     * @return
     */
    public static boolean checkUserName(String autopianum) {
        String str = "^[a-zA-Z0-9_-]{5,20}$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(autopianum);
        return m.matches();
    }

    /**
     * 判断是否为纯数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * "^[a-zA-Z0-9_-]{6,16}$"; 判断密码是否合法 "^[^\\s\\u4e00-\\u9fa5]{8,16}$";
     * 至少由一个字母和数字组成，8-16个字符组成，可以有特殊符号；格式验证（不能有空格）；
     *
     * @return
     */
    public static boolean checkPasswd(String passwd) {
        String str = "^[a-zA-Z0-9_-]{8,16}$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(passwd);
        return m.matches();
    }

    /**
     * 判断是否为邮箱
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        String str = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches() || email.contains("@51credit.com");
    }

    /**
     * 判断是否为手机号
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        String phone = "";
        if (mobiles.startsWith("+86")) {
            phone = mobiles.substring(3);
        } else {
            phone = mobiles;
        }
        // Changed by Eden,add '17*' supported
        Pattern p = Pattern
                .compile("^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0-9])|(18[^4,//D]))\\d{8}$");
        Matcher m = p.matcher(phone);
        return m.matches();
    }

    public static boolean isPackageAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE
    }

    public static void requestHttp(final String urlString, final String cookie, final String method, final String params, final Handler handler) {
        final StringBuffer sb = new StringBuffer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL(urlString);
                } catch (MalformedURLException exception) {
                    exception.printStackTrace();
                }
                HttpURLConnection httpURLConnection = null;
                try {
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    httpURLConnection.setRequestMethod(method);
                    httpURLConnection.setRequestProperty("Cookie", cookie);

                    if (!TextUtils.isEmpty(params)) {
                        //DataOutputStream流。
                        DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
                        //将要上传的内容写入流中
                        out.writeBytes(params);
                        //刷新、关闭
                        out.flush();
                        out.close();
                    }

                    int status = httpURLConnection.getResponseCode();
                    if (status == HttpURLConnection.HTTP_OK) {
                        InputStream ips = new BufferedInputStream(httpURLConnection.getInputStream());
                        BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "UTF-8"));

                        char[] buffer = new char[1024];
                        int bufferLength;
                        while ((bufferLength = reader.read(buffer, 0, buffer.length)) > 0) {
                            sb.append(buffer, 0, bufferLength);
                        }

                        reader.close();
                        ips.close();
                        httpURLConnection.disconnect();

                        Message message = handler.obtainMessage();
                        message.obj = sb.toString();
                        message.what = handler.hashCode();
                        handler.sendMessage(message);
                    } else {
                        throw new IOException("Server returned non-OK status: " + status);
                    }
                } catch (IOException exception) {
                    exception.printStackTrace();
                } finally {
                    if (httpURLConnection != null) {
                        httpURLConnection.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * @param value
     * @param defaultValue
     * @return
     * @Description 格式化String为int类型
     */
    public static int formatStringToInteger(String value, int defaultValue) {
        int result = defaultValue;
        if (TextUtils.isEmpty(value)) {
            value = "0";
        }
        try {
            result = Integer.parseInt(value);
        } catch (NumberFormatException e) {
        }
        return result;
    }

}
